﻿using System;
using System.Collections.Generic;

using Moe.ECamel.Common.Entities;
using Moe.ECamel.Client.ServiceProxies;

namespace Moe.ECamel.Client.Controllers
{
	public class LibrariesController : EntityController<Library>
	{
		public event EventHandler<LibraryEventArgs> LibraryUpdated;

		public Library NewLibrary(Library parentLibrary)
		{
			var library = new Library();

			library.ParentLibraryId = (parentLibrary == null ? (int?) null : parentLibrary.LibraryId);
			library.LibraryTypeId = (parentLibrary == null ? 1 : parentLibrary.LibraryTypeId + 1);
			library.LibraryType = ECamelHelper.LibraryTypes[library.LibraryTypeId];
			library.Address = "";
			library.Telephone = "";
			library.Fax = "";
			library.OpeningHours = "";
			library.Active = true;

			return library;
		}

		public override ECamelError Create(Library entity)
		{
			using (var serviceProxy = new LibraryServiceProxy())
			{
				return serviceProxy.CreateLibrary(entity);
			}
		}

		public override ECamelError Update(Library entity)
		{
			ECamelError error;

			using (var serviceProxy = new LibraryServiceProxy())
			{
				error = serviceProxy.UpdateLibrary(entity);
				if (error == null)
					AddOrUpdate(serviceProxy.GetLibraryById(entity.LibraryId));
			}

			return error;
		}

		public ECamelError UpdateLibraryStatus(Library library, bool active)
		{
			ECamelError error;

			using (var serviceProxy = new LibraryServiceProxy())
			{
				error = serviceProxy.UpdateLibraryStatus(library.LibraryId, active);
				if (error == null)
					AddOrUpdate(serviceProxy.GetLibraryById(library.LibraryId));
			}

			return error;
		}

		public Library GetLibrary(int libraryId)
		{
			foreach (var library in List)
				if (library.LibraryId == libraryId)
					return library;

			return null;
		}

		private void AddOrUpdate(Library library)
		{
			for (int i = 0; i < this.List.Count; i++)
			{
				if (this.List[i].LibraryId == library.LibraryId)
				{
					this.List[i] = library;
					RaiseLibraryUpdated(library);
					return;
				}
			}

			this.List.Add(library);			
		}

		protected override IList<Library> LoadList()
		{
			using (var serviceProxy = new LibraryServiceProxy())
			{
				return serviceProxy.GetAllLibraries();
			}
		}

		private void RaiseLibraryUpdated(Library library)
		{
			if (LibraryUpdated != null)
				LibraryUpdated(this, new LibraryEventArgs(library));
		}
	}

	public class LibraryEventArgs : EventArgs
	{
		public readonly Library Library;

		public LibraryEventArgs(Library library)
		{
			this.Library = library;
		}
	}
}